<template>
    <view
        class="updateCampaign"
        :style=" { paddingTop: paddingHeight + 'px', backgroundColor: bgColor, minHeight: minHeight + 'px' } "
    >
        <nav-bar title="运动"></nav-bar>
        <view class="t-h-container">
            <view class="details">
                <view class="d_card">
                    <view class="cell" @click="showCalendar = true">
                        <view class="c_l">日期</view>
                        <view class="c_r">{{ updateInfo.sportDate }}</view>
                    </view>
                    <view class="cell" @click="showProject = true">
                        <view class="c_l">运动项目</view>
                        <view class="c_r">{{ sportProject }}</view>
                    </view>
                    <view class="cell" @click="showStartTime = true">
                        <view class="c_l">运动开始时间</view>
                        <view class="c_r">{{ updateInfo.sportStartTime }}</view>
                    </view>
                    <view class="cell" @click="showDurationTime = true">
                        <view class="c_l">持续时间</view>
                        <view
                            class="c_r"
                        >{{ updateInfo.durationTime ? updateInfo.durationTime : 0 }}分钟</view>
                    </view>
                    <view class="cell">
                        <view class="c_l">心率</view>
                        <view class="c_r">
                            <u-input
                                type="number"
                                inputAlign="right"
                                placeholder="请输入心率"
                                border="none"
                                v-model=" updateInfo.currentHeartRate "
                            ></u-input>
                        </view>
                    </view>
                    <view class="cell">
                        <view class="c_l">消耗热量{{ updateInfo.kcal }}（Kcal）</view>
                        <view class="c_r kcal-btn" @click="handleGetConsumeHeat">计算消耗热量</view>
                    </view>
                </view>
                <view class="d_card RER-box" style="margin-top:32rpx">
                    <view class="cell" @click="handleShowsSportRER(2)">
                        <view class="c_l">运动前关联的RER测量</view>
                        <view class="c_r">
                            <u-icon name="edit-pen-fill" size="15"></u-icon>
                        </view>
                    </view>
                    <view>
                        <template v-if="sportBeforeForm.selectValue.length">
                            <view class="cell">
                                <view class="rer-table">
                                    <view class="rer-table-header">
                                        <view class="text">时间</view>
                                        <view class="text">代谢水平</view>
                                    </view>
                                    <view
                                        class="rer-table-row"
                                        v-for="(item, index) in sportBeforeForm.selectValue"
                                        :key=" index "
                                    >
                                        <view class="text">{{item.createTime }}</view>
                                        <view class="text">{{item.rerLevel }}</view>
                                    </view>
                                </view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="not-data">
                                <u-image
                                    width="64rpx"
                                    height="64rpx"
                                    :showMenuByLongpress="false"
                                    src="http://oss.antaimedical.com/images/pro/2024/10/671088aae4b0d615350f3099nt8UDhE3BBdK40e02078e4f477284337f925e806e8c9.png"
                                    :lazy-load="true"
                                ></u-image>
                                <view class="text">未关联数据</view>
                            </view>
                        </template>
                    </view>
                </view>
                <view class="d_card RER-box" style="margin-top:32rpx">
                    <view class="cell" @click="handleShowsSportRER2(3)">
                        <view class="c_l">运动后关联的RER测量</view>
                        <view class="c_r">
                            <u-icon name="edit-pen-fill" size="15"></u-icon>
                        </view>
                    </view>
                    <view>
                        <template v-if="sportAfterForm.selectValue.length">
                            <view class="cell">
                                <view class="rer-table">
                                    <view class="rer-table-header">
                                        <view class="text">时间</view>
                                        <view class="text">代谢水平</view>
                                    </view>
                                    <view
                                        class="rer-table-row"
                                        v-for="(item, index) in sportAfterForm.selectValue"
                                        :key=" index "
                                    >
                                        <view class="text" >{{ item.createTime }}</view>
                                        <view class="text" >{{ item.rerLevel }}</view>
                                    </view>
                                </view>
                            </view>
                        </template>
                        <template v-else>
                            <view class="not-data">
                                <u-image
                                    width="64rpx"
                                    height="64rpx"
                                    :showMenuByLongpress="false"
                                    src="http://oss.antaimedical.com/images/pro/2024/10/671088aae4b0d615350f3099nt8UDhE3BBdK40e02078e4f477284337f925e806e8c9.png"
                                    :lazy-load="true"
                                ></u-image>
                                <view class="text">未关联数据</view>
                            </view>
                        </template>
                    </view>
                </view>
            </view>
        </view>
        <view class="handle_c">
            <view class="delete_btn" @click="$u.throttle(del, 1500)">删除</view>
            <view class="save_btn" @click="$u.throttle(update, 1500)">保存</view>
        </view>

        <multiple-picker
            :show=" selectMultiple.show "
            :columns=" selectMultiple.columns "
            :defaultIndex=" selectMultiple.index "
            :title=" selectMultiple.title "
            @confirm=" confirmMultiple "
            @cancel="selectMultiple.show = false"
        ></multiple-picker>
        <multiple-picker
            :title="selectMultiple2.title"
            :show=" selectMultiple2.show "
            :columns=" selectMultiple2.columns "
            :defaultIndex=" selectMultiple2.index "
            @confirm=" confirmMultiple2 "
            @cancel="selectMultiple2.show = false"
        ></multiple-picker>
        <u-picker
            :show=" showProject "
            keyName="name"
            :defaultIndex=" [0] "
            @confirm=" selectProject "
            @cancel="showProject = false"
            @close="showProject = false"
            closeOnClickOverlay
            confirmColor="#545DDE"
            :columns=" columns "
        ></u-picker>
        <u-datetime-picker
            @confirm=" selectDurationTime "
            @cancel="showDurationTime = false"
            @close="showDurationTime = false"
            closeOnClickOverlay
            :show=" showDurationTime "
            mode="time"
        ></u-datetime-picker>
        <u-datetime-picker
            @confirm=" selectStartTime "
            @cancel="showStartTime = false"
            @close="showStartTime = false"
            :show=" showStartTime "
            v-model=" updateInfo.sportStartTime "
            closeOnClickOverlay
            mode="time"
        ></u-datetime-picker>
        <u-picker
            :show=" showGrade "
            :defaultIndex=" [0] "
            @confirm=" selectGrade "
            @cancel="showGrade = false"
            @close="showGrade = false"
            confirmColor="#545DDE"
            :columns=" columnsGrade "
            closeOnClickOverlay
        ></u-picker>
    </view>
</template>

<script>
import {
    delSportRecord,
    updateSportRecord,
    findSportType,
    findSportMeasureRecord,
    getConsumeHeat,
    findSportDetails
} from '@/api/index.js'
import { mapGetters } from 'vuex'
import multiplePicker from '@/components/multiple-picker/multiple-picker.vue'
const dayjs = require('@/utils/dayjs.min.js');
export default {
    data () {
        return {
            paddingHeight: uni.getStorageSync('navbarHeight'),
            userId: uni.getStorageSync("userId"),
            columns: [], // 项目列表
            columnsGrade: [
                ['低', '中', '高',]
            ],
            showProject: false,
            showDurationTime: false,
            showGrade: false,
            showStartTime: false,
            updateInfo: {
                durationTime: '10',
                sportDate: '',
                sportProject: 1,
                sportStartTime: '',
                currentHeartRate: '',
                kcal: ''
                // strengthGrade: '低',
            },
            sportProject: '',
            sportId: '',
            sportBeforeForm: {
                selectValue: [],
                selectIndex: [],
            },
            sportAfterForm: {
                selectValue: [],
                selectIndex: [],
            },
            selectMultiple: {
                show: false,
                title:'运动前',
                index: [],
                columns: [],
            },
            selectMultiple2: {
                show: false,
                title:'运动后',
                index: [],
                columns: [],
            },
            sportBeforeList: [],//运动前rer
            sportAfterList: [],//运动后rer
            sportType: ''
        }
    },
    computed: {
        ...mapGetters({
            userInfo: 'getUserInfo'
        }),
    },
    components: {
        multiplePicker
    },
    onLoad (OPTIONS) {
        let obj = JSON.parse(OPTIONS.info)
        console.log(obj);
        this.updateInfo.sportDate = dayjs(obj.sportDate).format('YYYY/MM/DD')
        this.updateInfo.sportStartTime = dayjs(obj.sportDate).format('HH:mm')
        this.updateInfo.durationTime = obj.durationTime
        this.sportId = obj.id
        this.sportProject = obj.sportProject
        this.fetchData()
        this.getFindSportMeasureRecord(2)
        this.getFindSportMeasureRecord(3)
        this.getFindSportDetails()
    },
    methods: {

        // 计算热量
        handleGetConsumeHeat () {
            let params = {
                bodyId: this.userInfo.id || this.userInfo.bodyId,
                currentHeartRate: this.updateInfo.currentHeartRate,
                durationTime: this.updateInfo.durationTime,
            }
            getConsumeHeat(params).then((res) => {
                if (res.code == 200) {
                    this.updateInfo.kcal = res.data
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            })
        },
        // 关联rer  start
        // 获取运动详情
        getFindSportDetails () {
            findSportDetails({ id: this.sportId }).then((res) => {
                const { sportData, afterList, beforeList } = res.data
                this.updateInfo.kcal = sportData.kcal
                this.updateInfo.currentHeartRate = sportData.currentHeartRate
                this.updateInfo.durationTime = sportData.durationTime
                this.sportAfterForm.selectIndex = afterList.map((val) => val.id)
                this.sportAfterForm.selectValue = afterList.map((val) => {
                    return {
                        label: `${val.createTime},${val.rerLevel}`,
                        createTime: val.createTime,
                        rerLevel: val.rerLevel,
                        value: val.id,
                    }
                })
                this.sportBeforeForm.selectIndex = beforeList.map((val) => val.id)
                this.sportBeforeForm.selectValue = beforeList.map((val) => {
                    return {
                        label: `${val.createTime},${val.rerLevel}`,
                        createTime: val.createTime,
                        rerLevel: val.rerLevel,
                        value: val.id,
                    }
                })
            }).catch((err) => {

            })
        },
        confirmMultiple (e) {
            this.sportBeforeForm.selectValue = e.selected
            this.sportBeforeForm.selectIndex = e.value;
            this.selectMultiple.show = false;
        },
        confirmMultiple2 (e) {
            this.sportAfterForm.selectValue = e.selected
            this.sportAfterForm.selectIndex = e.value;
            this.selectMultiple2.show = false;
        },
        handleShowsSportRER (sportType) {
            this.sportType = sportType
            this.selectMultiple.show = true
            this.selectMultiple.columns = this.sportBeforeList
            this.selectMultiple.index = this.sportBeforeForm.selectIndex
        },
        handleShowsSportRER2 (sportType) {
            this.sportType = sportType
            this.selectMultiple2.show = true
            this.selectMultiple2.columns = this.sportAfterList
            this.selectMultiple2.index = this.sportAfterForm.selectIndex
        },
        // 关联rer  end
        // 获取rer 测量数据
        getFindSportMeasureRecord (sportType) {
            let params = {
                sportDate: dayjs(this.updateInfo.sportDate).format('YYYY-MM-DD'),
                sportType,
                userId: this.userInfo.userId
            }
            findSportMeasureRecord(params).then((res) => {
                let arr = res.data.map((val) => {
                    return {
                        label: `${val.createTime} 代谢水平:${val.rerLevel}`,
                        createTime: val.createTime,
                        rerLevel: val.rerLevel,
                        value: val.id,
                    }
                })
                if (sportType == 2) {
                    this.sportBeforeList = arr
                } else {
                    this.sportAfterList = arr
                }
            })
        },
        // 获取运动类型
        async fetchData () {
            uni.showLoading({
                title: '加载中...'
            })
            try {
                const res = await findSportType()
                if (res.code == 200) {
                    this.columns[0] = res.data
                    let curPro = this.columns[0].find(item => {
                        return item.name == this.sportProject
                    })
                    this.updateInfo.sportProject = curPro.id
                }
            } catch (e) {
                //TODO handle the exception
            }
            uni.hideLoading()
        },
        async update () {
            uni.showLoading({
                title: '加载中...'
            })
            let params = {
                userId: this.userId,
                bodyId: this.userInfo.id || this.userInfo.bodyId,
                beforeRerRecord: this.sportBeforeForm.selectIndex.toString(),
                afterRerRecord: this.sportAfterForm.selectIndex.toString(),
                id: this.sportId,
                ...this.updateInfo
            }
            try {
                const res = await updateSportRecord(params)
                uni.hideLoading()
                if (res.code == 200) {
                    uni.showToast({
                        title: '修改成功'
                    })
                    setTimeout(() => {
                        uni.$emit('refreshData')
                        uni.navigateBack()
                    }, 1500)
                } else {
                    uni.showToast({
                        title: res.msg,
                        icon: 'none'
                    })
                }
            } catch (e) {
                //TODO handle the exception
                uni.hideLoading()
            }
        },
        async del () {
            uni.showLoading({
                title: '加载中...'
            })
            let params = {
                id: this.sportId
            }
            try {
                const res = await delSportRecord(params)
                uni.hideLoading()
                if (res.code == 200) {
                    uni.showToast({
                        title: '删除成功'
                    })
                    setTimeout(() => {
                        uni.$emit('refreshData')
                        uni.navigateBack()
                    }, 1500)
                }
            } catch (e) {
                //TODO handle the exception
                uni.hideLoading()
            }
        },
        // 确定选择项目
        selectProject (e) {
            this.sportProject = e.value[0].name
            this.updateInfo.sportProject = e.value[0].id
            this.showProject = false
        },
        // 确定选择等级
        selectGrade (e) {
            console.log(e);
            this.updateInfo.strengthGrade = e.value[0]
            this.showGrade = false
        },
        // 确定选择开始时间
        selectStartTime () {
            this.showStartTime = false
        },
        // 确定选择持续时间
        selectDurationTime (e) {
            console.log(e);
            this.showDurationTime = false
            let arr = e.value.split(':')
            let num
            if (Number(arr[0]) > 0) {
                num = Number(arr[0]) * 60 + Number(arr[1])
            } else {
                num = Number(arr[1])
            }
            this.updateInfo.durationTime = String(num)
        }
    }
}
</script>


<style lang="scss">
page {
    min-height: 100%;
    background: #f5f6fa;
}
</style>
<style lang="scss" scoped>
.t-h-container {
	padding: 0 26rpx 180rpx 26rpx;
	.details {
		.d_card {
			background: #fff;
			padding: 0 32rpx;
			border-radius: 32rpx;
			.cell {
				height: auto;
				padding: 32rpx 0;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				border-bottom: 2rpx solid #e6ebf5;
				&:last-child {
					border-bottom: 0;
				}
				.c_l {
					color: #1f2434;
				}
				.c_r {
					font-weight: 500;
					font-size: 28rpx;
					color: rgba(31, 36, 52, 0.5);
					/deep/.u-input__content__field-wrapper__field {
						font-weight: 500;
						font-size: 28rpx;
						color: rgba(31, 36, 52, 0.5);
					}
				}
				.kcal-btn {
					width: 225rpx;
					height: 72rpx;
					background: #1f2434;
					border-radius: 24rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #ffffff;
					display: flex;
					justify-content: center;
					align-items: center;
				}
			}
		}
		.RER-box {
			.cell {
				border-bottom: 0;
				.c_l {
					color: #1f2434;
				}
			}
			.rer-table {
				border-radius: 32rpx;
				overflow: hidden;
				.text {
					width: 310rpx;
					height: 64rpx;
					display: flex;
					justify-content: center;
					align-items: center;
					border: 2rpx solid #fff;
				}
				.rer-table-header {
					display: flex;
					justify-content: center;
					align-items: center;
					background: #fafafa;
				}
				.rer-table-row {
					display: flex;
					justify-content: center;
					align-items: center;
					background: #f4eefa;
				}
			}
			.not-data {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				padding-bottom: 32rpx;
				.text {
					margin-top: 16rpx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					font-size: 24rpx;
					color: #999999;
				}
			}
		}
	}
}
</style>